package com.domain.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间转换工具类
 */
public class DateUtils {
    private static Logger logger = LoggerFactory.getLogger(DateUtils.class);

    /**
     * 字符串转换为日期
     *
     * @param formatStr 要转换的字符串
     * @param format    自格式化样式（如：yyyy-MM-dd HH:mm:ss）
     * @return
     */
    public static Date strToDate(String formatStr, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(formatStr);

        } catch (ParseException e) {
            logger.error("时间转换错误", e);
            return null;
        }
    }

    /**
     * 日期转换为字符串
     *
     * @param date   要转换的日期
     * @param format 自格式化样式（如：yyyy-MM-dd HH:mm:ss）
     * @return
     */
    public static String dateToStr(Date date, String format) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            return simpleDateFormat.format(date);
        } catch (Exception e) {
            logger.error("时间转换错误", e);
            return "";
        }
    }

    /**
     * object 转  BigDecimal
     *
     * @param value
     * @return
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    /**
     * 今天加N天时间
     *
     * @param
     * @return
     */
    public static Date getNextDate(Integer n) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, +n); //今天的时间加一天  
        Date date = calendar.getTime();
        return date;
    }

    /**
     * 今天减N天时间
     *
     * @param
     * @return
     */
    public static Date getLessDate(Date datetime, Integer n) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.add(Calendar.DAY_OF_MONTH, -n);
        Date date = calendar.getTime();
        return date;
    }

    public static Date Month(Date datetime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(datetime);
        calendar.add(Calendar.MONTH, -1);
        Date date = calendar.getTime();
        return date;
    }

    /**
     * 结束时间减去开始时间(获取秒数)
     */
    public static long getTime(Date stareTime, Date endTime) {
        long result;
        SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime = d.format(stareTime);
        String endsTime = d.format(endTime);
        try {
            result = (d.parse(endsTime).getTime() - d.parse(beginTime).getTime()) / 1000;
            if (result <= 0) {
                result = 0;
            }
            return result;
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 得到两个时间相差的 秒数
     *
     * @return
     */
    public static long Datetime(Date date1, Date date2) throws ParseException {
        long l = date1.getTime() - date2.getTime();
        long time = l / 1000;
        return time;
    }

    /**
     * 获取日期（当前时间月份计算 1：下月   -1 上月）
     *
     * @return
     */
    public static Date dateCount(int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MONDAY, calendar.get(Calendar.MONDAY) + month);
        return calendar.getTime();
    }

    /**
     * 获取岁数
     *
     * @param birthDay
     * @return
     */
    public static int getAgeByBirthDay(Date birthDay) {
        if (!NotNullUtils.isNotNullObject(birthDay)) {
            return 0;
        }
        //获取当前系统时间
        Calendar cal = Calendar.getInstance();
        //如果出生日期大于当前时间，则抛出异常
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        //取出系统当前时间的年、月、日部分
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        //将日期设置为出生日期
        cal.setTime(birthDay);
        //取出出生日期的年、月、日部分
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        //当前年份与出生年份相减，初步计算年龄
        int age = yearNow - yearBirth;
        //当前月份与出生日期的月份相比，如果月份小于出生月份，则年龄上减1，表示不满多少周岁
        if (monthNow <= monthBirth) {
            //如果月份相等，在比较日期，如果当前日，小于出生日，也减1，表示不满多少周岁
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }


}
